import type { BaseResponse } from '../models/up_response.ts';
import { SerialPortFactory } from '../models/factories/SerialPortFactory';
import apiClient from '../utils/axiosInterceptors';

export class SerialServoService {
  /** 通用 POST 并校验 status */
  private static async postStatus(url: string, data: any): Promise<boolean> {
    const response = await apiClient.post<BaseResponse<null>>(url, data);
    if (response.data.status) {
      return true;
    }
    throw SerialPortFactory.createSerialError(
      response.data.message || 'Unknown error'
    );
  }

  static sendAngle(
    serial_id: string,
    protocol_id: number,
    angle: number
  ): Promise<boolean> {
    return this.postStatus(
      '/servo/angle',
      SerialPortFactory.createAngleRequest(serial_id, protocol_id, angle)
    );
  }

  static sendSpeed(
    serial_id: string,
    protocol_id: number,
    rpm: number
  ): Promise<boolean> {
    return this.postStatus(
      '/servo/speed',
      SerialPortFactory.createSpeedRequest(serial_id, protocol_id, rpm)
    );
  }

  static sendAngleRpm(
    serial_id: string,
    protocol_id: number,
    angle: number,
    rpm: number
  ): Promise<boolean> {
    return this.postStatus(
      '/servo/angle/rpm',
      SerialPortFactory.createAngleRpmRequest(
        serial_id,
        protocol_id,
        angle,
        rpm
      )
    );
  }

  static sendAngleLimit(
    serial_id: string,
    protocol_id: number,
    min: number,
    max: number
  ): Promise<boolean> {
    return this.postStatus(
      '/servo/angle/limit',
      SerialPortFactory.createAngleLimitRequest(
        serial_id,
        protocol_id,
        min,
        max
      )
    );
  }

  static sendVoltageLimit(
    serial_id: string,
    protocol_id: number,
    min: number,
    max: number
  ): Promise<boolean> {
    return this.postStatus(
      '/servo/voltage/limit',
      SerialPortFactory.createVoltageLimitRequest(
        serial_id,
        protocol_id,
        min,
        max
      )
    );
  }

  static restore(serial_id: string, protocol_id: number): Promise<boolean> {
    return this.postStatus(
      '/servo/restore',
      SerialPortFactory.createHttpRequest(serial_id, protocol_id)
    );
  }
}
